<template>
  <div class="md-editor">
    <md-editor
      v-model="text"
      theme="light"
      :preview="true"
      :showCodeRowNumber="true"
      :showPreview="true"
      :showToolbar="false"
      :showToc="true"
      :showPreviewOnly="false"
      language="zh-CN"
      @onChange="handleEditorChange"
      @onSave="handleSave"
    />
    <div class="message-toast" v-if="showMessage" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

interface IpcRenderer {
  send: (channel: string, ...args: any[]) => void;
  on: (channel: string, callback: (...args: any[]) => void) => () => void;
}

interface ElectronAPI {
  ipcRenderer: IpcRenderer;
}

declare global {
  interface Window {
    electron: ElectronAPI;
  }
}

const text = ref('');
const currentFilePath = ref<string | null>(null);
const hasUnsavedChanges = ref(false);
const currentContent = ref('');
const showMessage = ref(false);
const messageText = ref('');
const messageType = ref('');

// 添加编辑器内容变化处理函数
const handleEditorChange = (content: string) => {
  console.log('Editor content changed, new length:', content.length);
  text.value = content;
  currentContent.value = content;
  hasUnsavedChanges.value = true;
};

// 处理编辑器的保存事件
const handleSave = (content: string) => {
  console.log('Editor save triggered');
  saveFile();
};

// 更新编辑器内容的函数
const updateEditorContent = async (content: string) => {
  console.log('Updating editor content');
  console.log('Content length:', content.length);
  console.log('Content preview:', content.substring(0, 100));
  
  // 更新所有内容相关的状态
  text.value = content;
  currentContent.value = content;
  hasUnsavedChanges.value = false;
  
  // 等待 DOM 更新
  await nextTick();
  
  // 再次检查内容是否正确更新
  console.log('Editor content updated, current length:', text.value.length);
  if (text.value !== content) {
    console.error('Content mismatch after update!');
    // 尝试再次更新
    text.value = content;
    currentContent.value = content;
    await nextTick();
  }
};

// 保存文件
const saveFile = () => {
  if (!window.electron) {
    console.error('Electron API not available');
    return;
  }

  // 使用当前实际内容进行保存
  const contentToSave = text.value;
  console.log('Saving content, length:', contentToSave.length);
  console.log('Content preview:', contentToSave.substring(0, 100));

  if (currentFilePath.value) {
    console.log('Saving to existing file:', currentFilePath.value);
    window.electron.ipcRenderer.send('save-file', {
      content: contentToSave,
      path: currentFilePath.value
    });
  } else {
    console.log('Saving as new file');
    window.electron.ipcRenderer.send('save-file-as', {
      content: contentToSave,
      defaultPath: null
    });
  }
};

// 处理键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault();
    console.log('Save shortcut triggered');
    saveFile();
  }
};

const showToast = (text: string, type: 'success' | 'error') => {
  messageText.value = text;
  messageType.value = type;
  showMessage.value = true;
  setTimeout(() => {
    showMessage.value = false;
  }, 3000);
};

// 监听文件打开事件
onMounted(() => {
  console.log('App component mounted');
  console.log('Window electron object:', window.electron);
  
  window.addEventListener('keydown', handleKeyDown);

  if (!window.electron) {
    console.error('Electron API not available');
    return;
  }

  const cleanup: (() => void)[] = [];

  // 监听文件打开事件
  cleanup.push(
    window.electron.ipcRenderer.on('file-opened', async (data: { content: string; path: string }) => {
      console.log('Received file-opened event in renderer');
      console.log('File path:', data.path);
      console.log('Received content length:', data.content.length);
      console.log('Content preview:', data.content.substring(0, 100));

      currentFilePath.value = data.path;
      document.title = `MDNote - ${data.path}`;
      
      await updateEditorContent(data.content);
    })
  );

  // 监听错误事件
  cleanup.push(
    window.electron.ipcRenderer.on('error', (data: { type: string; message: string }) => {
      console.error('Received error:', data.type, data.message);
    })
  );

  // 监听保存响应
  cleanup.push(
    window.electron.ipcRenderer.on('save-file-reply', (data: { success: boolean; path?: string; error?: string }) => {
      console.log('Received save-file-reply:', data);
      if (data.success) {
        console.log('File saved successfully');
        hasUnsavedChanges.value = false;
        if (data.path) {
          currentFilePath.value = data.path;
          document.title = `MDNote - ${data.path}`;
        }
        showToast('文件保存成功！', 'success');
      } else {
        console.error('保存失败:', data.error);
        showToast(`保存失败: ${data.error}`, 'error');
      }
    })
  );

  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
    cleanup.forEach(fn => fn());
  });
});
</script>

<style>
@import 'md-editor-v3/lib/preview.css';

.md-editor {
  height: 100vh;
  width: 100%;
  position: relative;
}

:root {
  --md-color: #1e80ff;
  --md-hover-color: #1e80ff;
}

.message-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.message-toast.success {
  background-color: #67c23a;
}

.message-toast.error {
  background-color: #f56c6c;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 